﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using TracyGUI.View;
using SharedLib.WinFormMVCFramework;
using Tracy.DataModel;
using TracyGUI.View.EntryTabs;
using TracyGUI.Model;
using TracyGUI.View.UIComponent;
using System.Windows.Forms;
using System.Security.Permissions;

namespace TracyGUI.Controller.EntryTabs
{
    class ResourceTabPageViewController : ControllerBase<IResourceTabPageView>, IController<IResourceTabPageView>, ITabPageViewController
    {
        ITabPageViewController _parent;
        protected override IResourceTabPageView ResolveView()
        {
            return Tracy.TracyFacade.Instance.DIContainer.Resolve<IResourceTabPageView>();
        }

        public ResourceTabPageViewController(ITabPageViewController parent)
        {
            //Init
            _parent = parent;
            View.Name = "Resources";
            View.Text = Tracy.TracyFacade.Instance.LanguageManager.GetText("ResourceTabName");

            //View Events
            View.ResourcesRemoving += new EventHandler<SharedLib.GenericEventArgs<List<Resource>>>(View_ResourcesRemoving);
            View.ResourcesSendingToDownload += new EventHandler<SharedLib.GenericEventArgs<List<Resource>>>(View_ResourcesSendingToDownload);
            View.ResourcesCopyingURL += new EventHandler<SharedLib.GenericEventArgs<Resource>>(View_ResourcesCopyingURL);

            //Model Events
            Tracy.TracyFacade.Instance.ResourceProvider.ItemsAdded += new EventHandler<SharedLib.GenericEventArgs<IList<Resource>>>(ResourceProvider_ItemsAdded);
            Tracy.TracyFacade.Instance.ResourceProvider.ItemsChanged += new EventHandler<SharedLib.GenericEventArgs<IList<SharedLib.DataChangeSet<Resource>>>>(ResourceProvider_ItemsChanged);
            Tracy.TracyFacade.Instance.ResourceProvider.ItemsRemoved += new EventHandler<SharedLib.GenericEventArgs<IList<Resource>>>(ResourceProvider_ItemsRemoved);
        }

       

        #region View Events
        
        void View_ResourcesCopyingURL(object sender, SharedLib.GenericEventArgs<Resource> e)
        {
            //Clipboard operation may fail in a small possibility, it seems that the common solution to this is to simply ignore it. 
            bool success = false;
            try
            {
                Clipboard.SetDataObject(e.Data.Url, true, 2, 10);
                success = true;
            }
            catch (Exception ex)
            {
                //Do nothing
            }

            if (!success)
            {
                try
                {
                    Clipboard.SetDataObject(e.Data.Url, true, 2, 10);
                    success = true;
                }
                catch (Exception ex)
                {
                    //Do nothing
                }
            }
        }

        void View_ResourcesSendingToDownload(object sender, SharedLib.GenericEventArgs<List<Resource>> e)
        {
            Tracy.TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                foreach (Resource res in e.Data)
                {
                    DownloadCheckListViewController.SendResourceToDownload(this, res);
                }
            }, "UI Policy");
        }

        void View_ResourcesRemoving(object sender, SharedLib.GenericEventArgs<List<Resource>> e)
        {
            Tracy.TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                Tracy.TracyFacade.Instance.ResourceProvider.RemoveItems(e.Data);
            }, "UI Policy");
        }
        #endregion
        #region Model Events
        private bool IsResourceRelatedToCurrentView(Resource res)
        {
            if (res != null && res.Entry != null)
            {
                if (_parent is SingleEntryTabPageViewController)
                {
                    if (((SingleEntryTabPageViewController)_parent).Data.ID != res.Entry.ID) return false;
                }
                if (_parent is SearchResultTabPageViewController)
                {
                    if(!Tracy.TracyFacade.Instance.SearchEngine.IsResourceMatchingKeyword(res, ((SearchResultTabPageViewController)_parent).Keyword)) return false;
                }
                return true;
            }
            return false;
        }
        void ResourceProvider_ItemsAdded(object sender, SharedLib.GenericEventArgs<IList<Resource>> e)
        {
            List<Resource> resourcesToAdd = new List<Resource>();
            foreach (Resource res in e.Data)
            {
                if (IsResourceRelatedToCurrentView(res)) resourcesToAdd.Add(res);
            }
            if (resourcesToAdd.Count > 0)
            {
                View.LoadDataItemsToListView(resourcesToAdd, false);
            }
        }
        void ResourceProvider_ItemsChanged(object sender, SharedLib.GenericEventArgs<IList<SharedLib.DataChangeSet<Resource>>> e)
        {
            foreach (SharedLib.DataChangeSet<Resource> change in e.Data)
            {
                if (change.Data != null)
                {
                    if (IsResourceRelatedToCurrentView(change.Data))
                        View.UpdateDataItem(change.Data);
                }
            }
        }
        void ResourceProvider_ItemsRemoved(object sender, SharedLib.GenericEventArgs<IList<Resource>> e)
        {
            List<Resource> resourcesToRemove = new List<Resource>();
            foreach (Resource res in e.Data)
            {
                if (IsResourceRelatedToCurrentView(res))
                    resourcesToRemove.Add(res);
            }
            View.RemoveDataItems(resourcesToRemove);
        }
        #endregion
        #region Public Interfaces
        public void LoadResources(List<Resource> resources, Func<bool> stopCondition, bool clearView = true)
        {
            if (resources.Count > 10)
            {
                if (clearView && !stopCondition()) View.ClearListView();
                UIUpdateHelper.UpdateUIinTurn(50, resources, list => View.LoadDataItemsToListView(list, false), stopCondition);
            }
            else
            {
                View.LoadDataItemsToListView(resources, clearView);
            }
        }
        public void LoadResources(List<Resource> resources, bool clearView = true)
        {
            LoadResources(resources, () => false, clearView);
        }
        #endregion
        #region IController<ITabPageView> Members

        ITabPageView IController<ITabPageView>.View
        {
            get { return View; }
        }

        #endregion

        #region ViewState
        public void LoadViewState(ViewStateManager manager, System.Xml.XmlElement viewStateNode)
        {
            string sortColumn = viewStateNode.GetAttribute("sort-column");
            if (string.IsNullOrEmpty(sortColumn))
            {
                View.ListViewItems.SetSortColumn(Convert.ToInt32(sortColumn), viewStateNode.GetAttribute("sort-order"));
            }
        }

        public void SaveViewState(ViewStateManager manager, System.Xml.XmlElement viewStateNode, System.Xml.XmlDocument doc)
        {
            var sorter = (ListViewColumnSorter)View.ListViewItems.ListViewItemSorter;
            if (sorter != null)
            {
                viewStateNode.SetAttribute("sort-column", sorter.SortColumn.ToString());
                viewStateNode.SetAttribute("sort-order", (sorter.Order == SortOrder.Ascending) ? "asc" : "desc");
            }
        }
        #endregion
    }
}
